package hotel.controller;

import javafx.fxml.FXML;

import javafx.scene.control.Button;

import javafx.scene.control.TextField;
import javafx.scene.input.KeyCode;
import javafx.stage.Stage;
import hotel.common.Md5;
import hotel.common.MsgBox;
import hotel.dao.HotelDao;
import hotel.modal.User;
import javafx.event.ActionEvent;

import javafx.scene.control.PasswordField;

public class LoginController {
	@FXML
	private TextField userNameField;
	@FXML
	private PasswordField passwordField;
	@FXML
	private Button btnLogin;
	User user = null;
	
	@FXML
	public void initialize() {
		passwordField.setOnKeyReleased(event -> {
			if (event.getCode() == KeyCode.ENTER) {
				login();
			}
		});
	}
	
	// Event Listener on Button[#btnLogin].onAction
	@FXML
	public void onBtnLoginAction(ActionEvent event) {
		login();
	}
	
	public void login() {
		Boolean pass = true;
		String userName = userNameField.getText();
		String password = passwordField.getText();
		
		if(pass && userName.equals("")) {
			pass = false;
			MsgBox.showErrorDialog("登录错误", null, "用户名不能为空！");
		}
		
		if(pass && userName.length() > 20) {
			MsgBox.showErrorDialog("登录错误", null, "用户名过长！");
		}
		
		if(pass && password.equals("")) {
			pass = false;
			MsgBox.showErrorDialog("登录错误", null, "密码不能为空！");
		}
		
		if(pass) {
			User t = HotelDao.getUser(userName);
			if(t != null && Md5.getMD5(password).equals(t.getPassword())) {
				user.setAdmin(t.isAdmin());
				user.setEmployeeId(t.getEmployeeId());
				user.setPassword(t.getPassword());
				user.setUserName(t.getUserName());
				user.setModified(true);
				closeWindow();
			}else {
				MsgBox.showErrorDialog("登录错误", null, "用户名或密码错误！");
				passwordField.clear();
				passwordField.requestFocus();
			}
		}
		pass = true;
	}
	
	public void closeWindow() {
		Stage stage = (Stage)btnLogin.getScene().getWindow();
		stage.close();
	}
	
	public void setInitData(User user) {
		this.user = user;
		if(user != null) user.setModified(false);
	}
}
